package demo.insight;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author : feixiang.li
 * @since : 2025-09-17 10:36
 */
public class MyBufferedFileInputStream extends InputStream {


    private final byte[] buf;
    private final FileInputStream fis;
    private int bufPos = -1;
    private int capacity = -1;

    public MyBufferedFileInputStream(FileInputStream fileInputStream, Integer size) {
        this.fis = fileInputStream;
        this.buf = new byte[size];

    }

    @Override
    public int read() throws IOException {
        // 如果缓冲区有数据，则从缓冲区中读取数据
        if (buffCanRead()) {
            return readFormBuffer();
        }
        // 刷新缓冲区
        refushBuffer();
        // 再次判断缓冲区是否还有数据
        if (!buffCanRead()) {
            return -1;
        }
        // 读取缓冲区数据
        return readFormBuffer();
    }


    private void refushBuffer() throws IOException {
        bufPos = 0;
        capacity = fis.read(buf);
    }

    private boolean buffCanRead() {
        if (capacity == -1) {
            return false;
        }
        return bufPos < capacity;
    }

    private int readFormBuffer() {
        // buf是有符号位的。所以这里要去掉符号位 &0xff
        return buf[bufPos++] & 0xff;
    }


    @Override
    public void close() throws IOException {
        fis.close();
    }
}
